<template>
  <main>
    <div class="container">
      <h1>欢迎使用TODO待办事件</h1>
      <!-- 添加todo emit传值-->
      <TodoAdd :tid="todos.length" @addTodo="addTodo" />
      <!-- 根据条件过滤todos pros 传值-->
      <TodoFilter :selected="filterCondition" :changeFilterCondition="changeFilterCondition" />
      <!-- 展示todos pros 传值-->
      <TodoList :todos="filteredTodos" :changeState="changeState" />

    </div>
  </main>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, type Ref } from 'vue'
import TodoAdd from './components/TodoAdd.vue'
import TodoFilter from './components/TodoFilter.vue'
import TodoList from './components/TodoList.vue'

//todo类型
interface TodoType {
  id: number;
  content: string;
  completed: boolean;
}
// 定义todos
const todos: Ref<TodoType[]> = ref([])

//api
onMounted(async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos?_limit=4")
  // raw 生的 未加工的
  const rawTodos = await res.json()
  todos.value = rawTodos.map((todo: { id: number, title: string, completed: boolean }) => ({
    id: todo.id,
    content: todo.title,
    completed: todo.completed,
  }))
})

function addTodo(todoName: string) {
  const todo: TodoType = {
    id: todos.value.length + 1,
    content: todoName,
    completed: false
  }
  todos.value.push(todo)
  console.log(todos.value)
}

// 过滤逻辑
const filterCondition = ref("all")
const filteredTodos = computed(() => {
  switch (filterCondition.value) {
    case "done":
      return todos.value.filter((todo: TodoType) => todo.completed);
    case "todo":
      return todos.value.filter((todo: TodoType) => !todo.completed);
    default:
      return todos.value;
  }
});

// 切换条件
const changeFilterCondition = (condition: string) => {
  console.log(condition)
  filterCondition.value = condition
}

function changeState(todo: TodoType) {
  todo.completed = !todo.completed
}
</script>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Helvetica, "PingFang SC", "Microsoft Yahei", sans-serif;
}

main {
  width: 100vw;
  min-height: 100vh;
  display: grid;
  align-items: center;
  justify-items: center;
  background-color: rgb(203, 210, 240);
}

.container {
  width: 90%;
  max-width: 500px;
  box-shadow: 0 0 24px rgba(0, 0, 0, 0.15);
  border-radius: 24px;
  padding: 48px 24px;
  background-color: rgb(245, 246, 252);
}

h1 {
  margin-bottom: 24px;
  text-align: center;
  font-size: 24px;
  color: #414873;
}
</style>
